/**
 * 
 */
package org.lightcommons.template.commontemplate;

import java.io.Writer;
import java.util.Map;

import org.commontemplate.core.Context;
import org.commontemplate.core.ContextFactory;
import org.commontemplate.core.Template;
import org.commontemplate.tools.web.ModelMap;
import org.lightcommons.template.AbstractTemplate;
import org.lightcommons.util.Assert;

/**
 * @author gl
 * @since Jun 16, 2008
 */
public class CommonTemplateFacade extends AbstractTemplate {

	private final Template template;
	private final ContextFactory contextFactory;

	public CommonTemplateFacade(final Template template, final ContextFactory contextFactory) {
		super();
		Assert.notNull(template,"template must not be null");
		this.template = template;
		this.contextFactory = contextFactory;
	}

	@Override
	public void renderUnsafe(Object rootMap, Writer writer) throws Exception {
		final Context context = contextFactory.createContext(writer);
		if (rootMap instanceof Map) {
			context.pushLocalContext((Map) rootMap);
		} else {
			context.pushLocalContext(new ModelMap(rootMap));
		}
		template.render(context);		
	}
}
